package com.lemon.boot.common.service.impl;

import com.lemon.boot.common.service.MailService;
import com.lemon.boot.common.thread.pool.ExecutorThreadPoolGroup;
import lombok.Setter;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 李猛
 * @datetime 2024/7/18 18:11
 * @description TODO
 */
@Setter
@Service
public class MailServiceImpl implements MailService {
    @Resource
    private MailProperties mailProperties;

    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public void syncSend(String to, String subject, String content) {
        //同步发送邮件
        javaMailSender.send(simpleMailMessage(to, subject, content));
    }

    @Override
    public void asyncSend(String to, String subject, String content) {
        //异步发送邮件-线程池
        ExecutorThreadPoolGroup.messageExecutorService.execute(() -> asyncSend(to, subject, content));
    }

    /**
     * 封装邮件信息
     *
     * @param to
     * @param subject
     * @param content
     * @return
     */
    private SimpleMailMessage simpleMailMessage(String to, String subject, String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(to);
        mailMessage.setFrom(mailProperties.getUsername());
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        return mailMessage;
    }
}
